<?php

class Admin_LigaPresenter extends BasePresenter
{	
	public function renderNovy()
	{
		$form = $this['ligaForm'];
	}
	public function renderDefault()
	{
		$liga = new LigaModel();
		$this->template->ligy = $liga->findAll();

	}
	
	public function renderUpravit($id = 0)
	{
		$form = $this['ligaForm'];
		if (!$form->isSubmitted()) {
			$liga = new LigaModel();
			$row = $liga->findById($id)->fetch();
			if (!$row) {
				throw new NBadRequestException('Záznam nebyl nalezen.');
			}
			$form->setDefaults($row);
		}
	}
	
	public function renderSmazat($id = 0)
	{
		$form = $this['smazatForm'];
		$liga = new LigaModel();
		$soutez = new SoutezModel();
		$this->template->liga = $liga->findById($id)->fetch();
		
		//Je tato liga přiřazena nějaké soutěži?
		$liga_in_soutez = $soutez->findByLigaId($id)->fetchPairs('id','liga_id');
		if(count($liga_in_soutez) > 0)
			$this->template->enable_del = false;
		else
			$this->template->enable_del = true;
	
		
		if (!$this->template->liga) {
			throw new NBadRequestException('Liga nebyla nalezena');
		}
		
	}
	
	protected function createComponentSmazatForm()
	{
		$form = new NAppForm;
		
		$form->addSubmit('delete', 'Smazat')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět');
		$form->onSubmit[] = callback($this, 'smazatFormSubmitted');
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		$this->template->form = $form;
		return $form;
	}
	
	public function smazatFormSubmitted(NAppForm $form)
	{
		if ($form['delete']->isSubmittedBy()) {
			$liga = new LigaModel();
			$liga->delete($this->getParam('id'));
			$this->flashMessage('Liga byla odstraněna.');
		}

		$this->redirect('default');
	}
	
	protected function createComponentLigaForm()
	{
		$form = new NAppForm;
		$form->addText('nazev', 'Název ligy:');
	
		$form->addSubmit('save', 'Uložit')->getControlPrototype()->class('default');
		$form->addSubmit('cancel', 'Zpět')->getControlPrototype()->class('cancel')->setValidationScope(NULL);
		$form->onSubmit[] = callback($this, 'ligaFormSubmitted');
		
		$form->addProtection('Potvrďte prosím tento formulář znovu.');
		$this->template->form = $form;
		return $form;
	}
	public function ligaFormSubmitted(NAppForm $form)
	{
		if ($form['save']->isSubmittedBy()) {
			$id = (int) $this->getParam('id');
			$liga = new LigaModel;
			if ($id > 0) {
				$liga->update($id, $form->getValues());
				$this->flashMessage('Liga byla upravena.');
			} else {
				
				$liga->insert($form->getValues());
				
				$this->flashMessage('Liga byla vytvořena.');
			}
		}

		$this->redirect('default');
	}

}

